import React,{useEffect,memo} from 'react';
import { connect } from 'react-redux';
import { adressAction ,delAdressAction} from '../../store/actions';
import { useHistory } from 'react-router';
import Header from '../../components/Header';
import style from './index.module.scss';
const WrapHeader = memo(Header);

interface Iprops {
    getAdress: () => void,
    delAdress: (id:string) => void,
    addrList: Array<object>,
}
const Address:React.FC<Iprops> = props=>{
    const history = useHistory();
    useEffect(() => {
        props.getAdress()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    const {addrList} = props;
    const delFunc = (id:string)=>{
        if(window.confirm('确定删除吗')){
            props.delAdress(id);
            setTimeout(function(){
                props.getAdress()
            },200)
        }
    }
    return <div className={style.address}>
        <WrapHeader title="地址管理"/>
        <div className={style.content}>
        {
                addrList&&addrList.map((item:any)=>{
                    return <div 
                        className={[style.item,item.is_default?style.active:""].join(' ')} 
                        key={item.id}
                        >
                        <div
                            onClick={() => history.replace({pathname:'/addtoadr',state:{info:item}})}
                        >
                            <span>{item.name}</span>
                        </div>
                        <div
                            onClick={() => history.replace({pathname:'/addtoadr',state:{info:item}})}
                        >
                            <p>{item.mobile}</p>
                            <p>{item.full_region}</p>
                            <p>{item.address}</p>
                        </div>
                        <div>
                            <i className="iconfont icon-lajitong" onClick={()=>delFunc(item.id)} />
                        </div>
                    </div>
                })
        }
        </div>
        <div className={style.footer}>
            <button onClick={()=>history.replace({pathname:'/addtoadr',state:{info:""}})}>新建地址</button>
        </div>
    </div>
}
const mapStateToProps = (state: any) => {
    return state.adress
}
const mapDispatchToProps = (dispatch: Function) => {
    return {
        getAdress: () => {
            dispatch(adressAction());
        },
        delAdress: (id:string) => {
            dispatch(delAdressAction(id));
        },
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Address) 
